<?php

namespace App\Admin\Controllers;

use App\Admin\Repositories\Order;
use App\Admin\Repositories\User;
use App\Models\Account;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Show;
use Dcat\Admin\Http\Controllers\AdminController;
use Illuminate\Database\Eloquent\Collection;
use App\Models\Order as OrderModel;

class RechargeController extends AdminController
{

    //总充值金额
    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid(): Grid
    {
        return Grid::make(new Order(), function (Grid $grid) {
            $grid->model()->with(['user', 'payment_third_code_recharge'])
                ->where('type', '=', \App\Models\Order::RECHARGE)
                ->orderByDesc('id');

            $grid->column('id');
            $grid->column('user.tiktokno', trans('user.fields.tiktokno'))->display(function ($var){
                return $this->user_id."({$var})";
            });
            $grid->column('amount', trans('order.fields.amount'))->display(function ($var) {
                return $var / 100;
            });
            $grid->column('payment_third_code_recharge.title', '通道')->display(function($var){
                if($this->payment_third_code_recharge && $this->payment_third_code_recharge->payment){
                    return $this->payment_third_code_recharge->payment->title . '['.$this->payment_third_code_recharge->title.']';
                }else{
                    return "人工";
                }
            });
            $grid->column('no', trans('order.fields.no'));
            $grid->column('payment_no', trans('order.fields.payment_no'));
            $grid->column('state', trans('order.fields.state'))->using([
                \App\Models\Order::REVIEW => '审核中',
                \App\Models\Order::PENDING => '进行中',
                \App\Models\Order::SUCCESS => '成功',
                \App\Models\Order::FAILED => '失败',
                \App\Models\Order::CANCEL => '取消',
                \App\Models\Order::REFUSE => '拒绝',
            ], '未知')->dot([
                \App\Models\Order::REVIEW => 'warning',
                \App\Models\Order::PENDING => 'info',
                \App\Models\Order::SUCCESS => 'success',
                \App\Models\Order::FAILED => 'danger',
                \App\Models\Order::CANCEL => 'default',
                \App\Models\Order::REFUSE => 'primary',
            ], 'warning');

            $grid->column('remark', '理由');


            $grid->column('number', trans('recharge.fields.number'))->display(function () {
                if ($this->state == \App\Models\Order::SUCCESS) {
                    return \App\Models\Order::where('state', \App\Models\Order::SUCCESS)->where('type', \App\Models\Order::RECHARGE)->where('id', '<=', $this->id)->where('user_id', $this->user_id)->count();
                }
                return '';
            });
            $grid->column('created_at');
            //$grid->column('updated_at');
            $grid->quickSearch(['user_id','user.tiktokno', 'no'])->placeholder(trans('order.fields.no') . '/' . trans('user.fields.tiktokno'));
            $grid->filter(function (Grid\Filter $filter) {
                $filter->equal('id');
                $filter->like('user.id', trans('user.fields.id'));
                $filter->like('user.tiktokno', trans('user.fields.tiktokno'));
                $filter->between('amount', trans('order.fields.amount'));
                $filter->equal('state', trans('order.fields.state'))->select([
                    \App\Models\Order::PENDING => '进行中',
                    \App\Models\Order::SUCCESS => '成功',
                    \App\Models\Order::FAILED => '失败'
                ]);
                $filter->between('created_at')->datetime();

                $filter->like('no', trans('order.fields.no'));
                $filter->like('payment_no', trans('order.fields.payment_no'));
            });


            $grid->footer(function ($collection) use ($grid) {
                $query = \App\Models\Order::query();

                // 拿到表格筛选 where 条件数组进行遍历
                $grid->model()->getQueries()->unique()->each(function ($value) use (&$query) {
                    if (in_array($value['method'], ['paginate', 'get', 'orderBy', 'orderByDesc'], true)) {
                        return;
                    }

                    $query = call_user_func_array([$query, $value['method']], $value['arguments'] ?? []);
                });

                // 查出统计数据
                $data = $query->where('state','=',\App\Models\Order::SUCCESS)->where('type', '=', \App\Models\Order::RECHARGE)->sum('amount') /100;

                $htmlstr = '<div class="d-flex" style="font-size: 16px;">总充值：<strong>'.$data.'</strong></div>';

                return $htmlstr;
            });


            //$grid->disableCreateButton();
            //$grid->disableActions();
            $grid->disableBatchActions();
            $grid->disableRowSelector();
            $grid->disableViewButton();
            $grid->disableDeleteButton();
            $grid->showQuickEditButton();
            $grid->export();
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Form::make(new \App\Models\Order(), function (Form $form) {

            if ($form->isCreating()) {
                $form->select('user_id')->options(\App\Models\User::getUsers())->required();
                $form->text('amount')->required()->saving(function ($var) {
                    $var = $var * 100;
                    return $var;
                });
                $form->text('remark','理由')->help('注意使用对应国家语言');
                $form->hidden('no')->default(only_code());
                $form->hidden('state')->default(\App\Models\Order::SUCCESS);
                $form->hidden('type')->default(1);
                $form->hidden('closed')->default(1);
            }
            if ($form->isEditing()) {
                $form->text('remark','理由')->help('注意使用对应国家语言');
            }


            $form->saved(function (Form $form, $result) {
                // 判断是否是新增操作
                if ($form->isCreating()) {
                    // 自增ID
                    $newId = $result;

                    if (! $newId) {
                        return $form->error('数据保存失败');
                    }

                    //清缓存 加流水
                    $order = \App\Models\Order::where('id','=',$newId)->first();
                    $user = \App\Models\User::where('id', '=', $order->user_id)->first();
                    $user->increment('balance', $order->amount);
                    $user->save();
                    (new Account())->store($order->user_id, $order->amount, Account::RECHARGE, 0, $order->id);

                }

                // 修改操作
            });

        });



    }




}
